package com.xxxx.controller.UserServlet;

import com.google.gson.JsonObject;
import com.xxxx.entity.User;
import com.xxxx.entity.vo.MessageModel;
import com.xxxx.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login") //添加注解

public class Login extends HttpServlet {

    //实例化UserService对象
    private UserService userService = new UserService();


    /**
     * 用户登录
     1.接收客户端的请求(接收参数: 电子邮箱, 密码)
     2.调用service层的方法, 返回消息模型对象
     3.判断消息模型状态码
     如果状态码是失败
     将消息模型对象设置到request作用域中, 请求转发跳转到login.jsp
     如果状态码是成功
     将消息模型中的用户信设置到session作用域中, 重定向跳转到index.jsp
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收客户端的请求(接收参数: 电子邮箱, 密码)
        String uemail = request.getParameter("email");
        String upwd = request.getParameter("password");
        HttpSession session = request.getSession();
        //新建一个cookie，将sessionid放入
        Cookie cookie = new Cookie("user", session.getId());
        //设置cookie的失效时间
        cookie.setMaxAge(30*60);
        //添加cookie
        response.addCookie(cookie);
        //2.调用service层的方法, 返回消息模型对象
        MessageModel messageModel = userService.userLogin(uemail, upwd);
        //3.判断消息模型状态码
        if(messageModel.getCode() == 1){ //成功
            //将消息模型中的用户信设置到session作用域中, 重定向跳转到index.jsp
            request.getSession().setAttribute("user", messageModel.getObject());
            User user= (User) messageModel.getObject();
            if("1".equals(user.getUserId())){
                request.getSession().setAttribute("admin", messageModel.getObject());
            }
            JsonObject object=new JsonObject();
            object.addProperty("code", messageModel.getCode());
            response.getOutputStream().write(object.toString().getBytes("UTF-8"));
            response.setContentType("text/json; charset=UTF-8");
        } else { //失败
            //将消息模型对象设置到request作用域中, 请求转发跳转到login.jsp
            JsonObject object=new JsonObject();
            object.addProperty("msg", messageModel.getMsg());
            object.addProperty("code", messageModel.getCode());
            response.getOutputStream().write(object.toString().getBytes("UTF-8"));
            response.setContentType("text/json; charset=UTF-8");
        }

    }


}
